﻿# -*- coding: utf-8 -*-

from twisted.protocols import basic
from twisted.internet import protocol, reactor
import zlib

from world import *
from netDefines import *
from Materials.wood import *
from Creatures.goblin import *

world = None

class ServerNetwork(basic.LineReceiver):
    def connectionMade(self):
        print "Got new client!"
        self.factory.clients.append(self)
        self.sendDisplayUpdate()

    def connectionLost(self, reason):
        print "Lost a client!"
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        print "received command", repr(line[0:3]), "from", self.transport.getPeer()
        command = line[0:3]
        data = self.decompressData(line[3:])
        if command == DISPLAY_REQUEST:
            pos_x = int(data[0:4])
            pos_y = int(data[4:8])
            z = int(data[8:12])
            self.sendMessage(DISPLAY_UPDATE, self.getCurrentDisplay(pos_x, pos_y, z, 42, 28))
        
    def compressData(self, data):
        return zlib.compress(data)

    def decompressData(self, data):
        return zlib.decompress(data)

    def sendMessage(self, code, message):
        print 'sending', code, message
        self.sendLine(code + self.compressData(message))
        
    def getCurrentDisplay(self, pos_x, pos_y, z, width, height):
        global world
        screenicons = ""
        screencolours = ""
        screenbgs = ""
        for cx in xrange(width):
            x = cx + pos_x
            for cy in xrange(height):
                y = cy + pos_y
                c = world.getCell((x, y, z))
                icon = c.getIcon()
                screenicons += icon[0]
                screencolours += str(icon[1][0]).rjust(3, "0") + str(icon[1][1]).rjust(3, "0") + str(icon[1][2]).rjust(3, "0")
                screenbgs += str(icon[2][0]).rjust(3, "0") + str(icon[2][1]).rjust(3, "0") + str(icon[2][2]).rjust(3, "0")

        return screenicons + screencolours + screenbgs
                
    def sendDisplayUpdate(self):
        self.sendMessage(DISPLAY_UPDATE, self.getCurrentDisplay(0, 0, 0, 42, 28))

if __name__ == '__main__':
    factory = protocol.ServerFactory()
    factory.protocol = ServerNetwork
    factory.clients = []

    world = World((42, 28, 4))
    world.setCell((3, 3, 3), Cell(Wood()))
    c = world.getCell((3, 3, 3))
    c.addCreature(Goblin())

    reactor.listenTCP(1079, factory)
    reactor.run()

